<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class install_controller extends Controller {

	public function __construct() {
		parent::__construct();
		load_helper('global');
		$this->initi();
	}

	public function initi(){
		$lockfile = BASEPATH.'data/install.lock';
		//touch($lockfile);
		if(file_exists($lockfile)) {
			show_error("Puzzzing social has already installed!");
		}
		$this->language = config_item('language');
		$this->theme = 'install';
		$this->thcolor = 'default';
	}

	public function render($tpl,$vars){
		return $this->template->display($tpl,$vars,$this->theme,$this->thcolor,true,0);
	}

	public function output($tpl,$vars=array(),$need_header_footer=true){
		$this->need_header_footer = $need_header_footer;
		$this->template->display($tpl,$vars,$this->theme,$this->thcolor,false,0);
	}

	public function mredirect($url,$message,$time=3){
		$this->template->display('common/message.htm',array('url'=>$url,'message'=>$message,'time'=>$time),$this->theme,$this->thcolor,false,0);
	}

	public function ajax_success_response($data,$message){
		$response = array('success' => true, 'data' => $data, 'message'=>$message);
		$content = json_encode($response);
		$this->template->content_display($content);
	}

	public function ajax_failed_response($message='failed_msg',$data=null){
		$response = array('success' => false,'message'=>$message,'data'=>$data);
		$content = json_encode($response);
		$this->template->content_display($content);
	}

	public function index(){
		$this->output("step1");
	}

	public function step2(){
		$env_check = array(
				'phpversion'=> array('label'=>'PHP Version',"need_version"=> '5.2.0',"curr_version"=>phpversion(),"check"=>true)
		);

		$func_check = array(
				'mysql_connect'=>array('label'=>'Mysql','check'=>false),
				'iconv'=>array('label'=>'ICONV','check'=>false),
				'gd_info'=>array('label'=>'GD','check'=>false),
				'json_encode'=>array('label'=>'JSON','check'=>false),
				'curl_init'=>array('label'=>'Curl','check'=>false),
				'fsockopen'=>array('label'=>'fsockopen','check'=>false),
				'puzz_run'=>array('label'=>'Puzzcore','check'=>false)
		);
		$dir_check = array(
				"data" => 					array("check"=>false,"attrib"=> 0),
				"data/attachments" => 		array("check"=>false,"attrib"=> 0),
				"data/template" => 		array("check"=>false,"attrib"=> 0),
				"data/group" => 		array("check"=>false,"attrib"=> 0),
				"data/topic" => 		array("check"=>false,"attrib"=> 0),
				"data/store" => 		array("check"=>false,"attrib"=> 0),
				"data/cache" => 		array("check"=>false,"attrib"=> 0),
				"config" => 		array("check"=>false,"attrib"=> 0),
				"logs" => 		array("check"=>false,"attrib"=> 0),
				//"config/database_default.php" => 		array("check"=>false,"attrib"=> 0),
		);
			
		$final_check = true;
		foreach($env_check as $key=>$value) {
			if (strnatcmp($env_check[$key]['curr_version'],$env_check[$key]['need_version']) < 0) {
				$env_check[$key]['check'] = false;
				$final_check = false;
			}
		}

		foreach($func_check as $key=>$value) {
			$func_check[$key]['check'] = function_exists($key);
			if (!$func_check[$key]['check']) $final_check = false;
		}

		foreach($dir_check as $key=>$value) {
			$dir_check[$key]['check'] = is_really_writable(BASEPATH.$key);
			if (!$dir_check[$key]['check']) $final_check = false;
		}

		$this->env_check = $env_check;
		$this->func_check = $func_check;
		$this->dir_check = $dir_check;
		$this->final_check = $final_check;

		$this->output("step2");
	}

	public function step3(){
		if($this->input->post()){
			$db = array(
					'hostname'=> $this->input->post("hostname"),
					'port' => $this->input->post("db_port"),
					'username'=> $this->input->post("db_login"),
					'password' => $this->input->post("db_password"),
					'database' => $this->input->post("db_database"),
					'dbprefix' => $this->input->post("db_prefix"),
			);
			$admin = array(
					'email'=> $this->input->post("admin_email"),
					'nickname'=> $this->input->post("admin_nickname"),
					'password' => $this->input->post("admin_password"),
			);

			$default_config = $config = array();
			$default_configfile = BASEPATH.'config/database_default.php';
			
			if(!file_exists($default_configfile)) {
				exit('database_default.php was lost, please reupload this  file.');
			} else {
				include $default_configfile;
				$default_config = $config;
			}

			$config['default'] = $db;
			
			save_config_file(BASEPATH.'config/database.php', $config, $default_config);
			$do_install = $this->do_install($db,$admin);
			if($do_install['status'] != 200) {
				$this->install_error = $do_install;
				$this->output("step3");
			}else{
				$lockfile = BASEPATH.'data/install.lock';
				touch($lockfile);
				$this->step4();
			}
		}else{
			$this->output("step3");
		}
	}

	public function step4(){
		$this->front_page = site_url('welcome/index');
		$this->admin_page = site_url('admin/login');
		$this->output("step4");
	}

	private function do_install($db_config,$admin_userinfo = array()){

		//初使化数据库
		$link = mysql_connect($db_config['hostname'].':'.$db_config['port'], $db_config['username'],  $db_config['password']);
		if (!$link) {
			return array('status'=>500,'msg'=>'数据库链接失败，错误提示：<br />'. mysql_error());
		}
		if(!mysql_select_db($db_config['database'], $link)){
			return array('status'=>500,'msg'=>'数据库不存在，请先建立数据库后再进行安装');
		}
		mysql_query("SET NAMES utf8");

		$exist_table = $db_config['dbprefix'].'ptx_';
		$query = "SHOW TABLES LIKE  '%{$exist_table}%'";

		$result = mysql_query($query);
		if ( mysql_num_rows($result) > 0 ) {
			return array('status'=>500,'msg'=> '数据表已存在，如果需要重新安装请先行删除原有数据表。' );
		}

		//导入SQL文件
		$sql = explode(";",file_get_contents(BASEPATH.'themes/install/install.sql'));
		foreach($sql as $query){
			if(trim($query) == '') continue;
			$query = str_replace('{dbpre}', $db_config['dbprefix'], $query);
			$result = mysql_query($query);
			if (!$result) {
				$message  = 'Invalid query: ' . mysql_error() . "\n<br />";
				$message .= 'Whole query: ' . $query;
				return array('status'=>500,'msg'=> $message );
			}
		}
		$sql = explode("**spt**",file_get_contents(BASEPATH.'themes/install/settings.sql'));
		foreach($sql as $query){
			if(trim($query) == '') continue;
			$query = str_replace('{dbpre}', $db_config['dbprefix'], $query);
			$result = mysql_query($query);
			if (!$result) {
				$message  = 'Invalid query: ' . mysql_error() . "\n<br />";
				$message .= 'Whole query: ' . $query;
				return array('status'=>500,'msg'=> $message );
			}
		}
		//创建管理员账号
		$admin_email = $admin_userinfo['email'];
		$admin_pass = md5($admin_userinfo['password']);
		$admin_nickname = $admin_userinfo['nickname'];
		$ui_setting['style'] = 'puzzing';
		$ui_setting['color'] = 'default';
		$ui_setting = serialize($ui_setting);
		$credit_name['credits'] = '积分';
		$credit_name['ext_credits_1'] = '威望';
		$credit_name['ext_credits_2'] = '体力';
		$credit_name['ext_credits_3'] = '激情';
		$credit_name = serialize($credit_name);
		
		$gsetting['siteclosed'] = FALSE;
		$vs = array ('Taobao','Sina','Renren','QQ','Facebook','Twitter');
		foreach ($vs as $v){
			$lowerkey = strtolower($v);
			$gsetting['vendors'][$lowerkey] = array(
							'param'=>$v,
							'open'=>FALSE,
							'appkey'=>'',
							'appsecret'=>'',
							'callback'=>'',
							'pid'=>''
					);
		}
		$gsetting['vcode_setting']['login'] = TRUE;
		$gsetting['vcode_setting']['register'] = TRUE;
		$gsetting['style'] = 'puzzing';
		$gsetting['color'] = 'default';
		$gsetting = serialize($gsetting);
		
		$prefix = $db_config['dbprefix'];
		$query = "INSERT INTO `{$prefix}ptx_settings` (`setting_id`, `set_key`, `set_value`) VALUES ('1','ui_styles','{$ui_setting}');";
		mysql_query($query);

		$query = "INSERT INTO `{$prefix}ptx_settings` (`setting_id`, `set_key`, `set_value`) VALUES ('2','credit_name','{$credit_name}');";
		mysql_query($query);

		$query = "INSERT INTO `{$prefix}ptx_settings` (`setting_id`, `set_key`, `set_value`) VALUES ('3','global_setting','{$gsetting}');";
		mysql_query($query);
		
		$create_time = mktime();
		$query = "INSERT INTO `{$prefix}ptx_user` (`email`, `passwd`, `nickname`, `create_time`) VALUES ('{$admin_email}','{$admin_pass}','{$admin_nickname}','{$create_time}'); ";
		$result = mysql_query($query);
		if($result){
			$query = "INSERT INTO `{$prefix}ptx_user_usergroup` (`usergroup_id`, `user_id`, `create_time`) VALUES ('1','1','{$create_time}'); ";
			$result = mysql_query($query);
		}
		if (!$result) {
			return array('status'=>500,'msg'=> '管理员账号建立失败，请重新安装。<br />如果仍然失败，请与oNightJar.com联系。' );
		}
		
		

		delete_files(BASEPATH.'data/template/');

		
		$default_config = $config = array();
		$default_configfile = BASEPATH.'config/global_default.php';
			
		if(!file_exists($default_configfile)) {
			exit('global_default.php was lost, please reupload this  file.');
		} else {
			include $default_configfile;
			$default_config = $config;
		}
		
		$config['default_module'] = 'welcome/index';
			
		save_config_file(BASEPATH.'config/global.php', $config, $default_config);
		
		return array('status'=>200,'msg'=> '数据库导入成功' );

	}

}


function save_config_file($filename, $config, $default) {
	$config = setdefault($config, $default);
	$date = gmdate("Y-m-d H:i:s", time() + 3600 * 8);
	$content = <<<EOT
<?php
 if ( ! defined('BASEPATH')) exit('No direct script access allowed');
EOT;
	$content .= getvars(array('config' => $config));
	$content .= "\r\n// ".str_pad('  THE END  ', 50, '-', STR_PAD_BOTH)." //\r\n\r\n?>";
	file_put_contents($filename, $content);
}

function setdefault($var, $default) {
	foreach ($default as $k => $v) {
		if(!isset($var[$k])) {
			$var[$k] = $default[$k];
		} elseif(is_array($v)) {
			$var[$k] = setdefault($var[$k], $default[$k]);
		}
	}
	return $var;
}

function getvars($data, $type = 'VAR') {
	$evaluate = '';
	foreach($data as $key => $val) {
		if(!preg_match("/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/", $key)) {
			continue;
		}
		if(is_array($val)) {
			$evaluate .= buildarray($val, 0, "\${$key}")."\r\n";
		} else {
			if(is_bool($var)){
				$val = $val?'TRUE':'FALSE';
			}
			$val = addcslashes($val, '\'\\');
			$evaluate .= $type == 'VAR' ? "\$$key = '$val';\n" : "define('".strtoupper($key)."', '$val');\n";
		}
	}
	return $evaluate;
}

function buildarray($array, $level = 0, $pre = '$_config') {
	static $ks;
	if($level == 0) {
		$ks = array();
		$return = '';
	}

	foreach ($array as $key => $val) {
		if($level == 0) {
			$newline = str_pad('  CONFIG '.strtoupper($key).'  ', 70, '-', STR_PAD_BOTH);
			$return .= "\r\n// $newline //\r\n";
			if($key == 'admincp') {
				$newline = str_pad(' Founders: $_config[\'admincp\'][\'founder\'] = \'1,2,3\'; ', 70, '-', STR_PAD_BOTH);
				$return .= "// $newline //\r\n";
			}
		}

		$ks[$level] = $ks[$level - 1]."['$key']";
		if(is_array($val)) {
			$ks[$level] = $ks[$level - 1]."['$key']";
			$return .= buildarray($val, $level + 1, $pre);
		} else {
			if(is_bool($var)){
				$val = $val?'TRUE':'FALSE';
			}
			$val =  is_string($val) || strlen($val) > 12 || !preg_match("/^\-?[1-9]\d*$/", $val) ? '\''.addcslashes($val, '\'\\').'\'' : $val;
			$return .= $pre.$ks[$level - 1]."['$key']"." = $val;\r\n";
		}
	}
	return $return;
}
function delete_files($path, $del_dir = FALSE, $level = 0)
{
	// Trim the trailing slash
	$path = rtrim($path, DIRECTORY_SEPARATOR);

	if ( ! $current_dir = @opendir($path))
	{
		return FALSE;
	}

	while (FALSE !== ($filename = @readdir($current_dir)))
	{
		if ($filename != "." and $filename != "..")
		{
			if (is_dir($path.DIRECTORY_SEPARATOR.$filename))
			{
				// Ignore empty folders
				if (substr($filename, 0, 1) != '.')
				{
					delete_files($path.DIRECTORY_SEPARATOR.$filename, $del_dir, $level + 1);
				}
			}
			else
			{
				unlink($path.DIRECTORY_SEPARATOR.$filename);
			}
		}
	}
	@closedir($current_dir);

	if ($del_dir == TRUE AND $level > 0)
	{
		return @rmdir($path);
	}

	return TRUE;
}
?>